package fun.stgoder.test1;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.*;

public class TestThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TFactory factory = new TFactory();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                4,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                factory, // Executors.defaultThreadFactory();
                (r, executor) -> {
                    System.out.println("drop");
                });


        /*for (int i = 0; i < 100; i++) {
            threadPoolExecutor.execute(() -> {
                TestUtil.sleepSeconds(3);
                System.out.println("end");
            });
        }*/

        final StringBuilder res = new StringBuilder();
        Callable<StringBuilder> callable = Executors.callable(() -> {
            System.out.println("begin");
            res.append("do");
            TestUtil.sleepSeconds(5);

            System.out.println("end");
        }, res);

        Future<StringBuilder> future = threadPoolExecutor.submit(callable);
        StringBuilder stringBuilder = future.get();


        System.out.println("res " + stringBuilder);

    }
}

class TFactory implements ThreadFactory {

    private AtomicInteger num = new AtomicInteger(0);

    @Override
    public Thread newThread(Runnable r) {
        System.out.println(num.incrementAndGet());
        return new Thread(r);
    }
}
